package com.gopay.commons.validator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;

import com.gopay.commons.validator.form.ErrorMessage;
import com.gopay.commons.validator.form.Field;
import com.gopay.commons.validator.form.Form;

/**
 * Form验证服务实现类
 * 
 * @DefaultFormService.java
 * @author yaobo
 * @2012-12-26 上午09:54:04 www.gopay.com.cn Inc.All rights reserved.
 */
public class DefaultFormService implements FormService {
    protected static Map<String, Form> forms = null;
    private Map<String, String> errorMessages = null;
    private List<String> filePath = new ArrayList<String>();
    private Object object = new Object();
    private boolean validFlag;

    /**
     * 获取项目所需的验证文件并构建成map列表
     * 
     * @return
     */
    @Override
    public Map<String, Form> getForms() {
        synchronized (object) {
            if (forms == null) {
                buildValidator(filePath);
            }
            return forms;
        }
    }

    /**
     * 表单验证
     */
    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public boolean isValid(Form form) {
        validFlag = true;
        errorMessages = new HashMap<String, String>();
        Map<String, Field> fields = form.getFields();
        if (fields == null) {
            return false;
        }

        Iterator iter = fields.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, Field> entry = (Map.Entry<String, Field>) iter.next();
            Field field = entry.getValue();

            isField(field, errorMessages);
        }

        return this.validFlag;
    }

    /**
     * 表单验证
     * 
     * @param form
     * @param obj
     * @return
     */
    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public boolean isValid(Form form, Map<String, String> values) {
        if (values == null) {
            return false;
        }

        Map<String, Field> fields = form.getFields();
        if (fields == null) {
            return false;
        }

        Iterator iter = fields.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, Field> entry = (Map.Entry<String, Field>) iter.next();
            Field field = entry.getValue();
            field.setStringValue(values.get(field.getFieldName()));
        }

        return isValid(form);
    }

    /**
     * 对field的验证
     */
    private void isField(Field field, Map<String, String> errorMessages) {
        ErrorMessage errorMessage = ValidatorTools.validator(field);
        if (errorMessage != null) {
            this.validFlag = false;
            errorMessages.put(errorMessage.getFieldName(), errorMessage.getMessage());
        }
    }

    /**
     * 
     * @param filePath
     */
    private void buildValidator(List<String> filePath) {
        ValidatorDefine define = new SystemValidatorDefine();
        Document[] documents = null;
        Document document = null;
        try {
            documents = define.read(filePath);
            document = define.merge(documents);
        } catch (DocumentException de) {
            de.printStackTrace();
        }
        FormBuilder formBuilder = new FormBuilder();
        formBuilder.builder(document);
    }

    @Override
    public Map<String, String> getErrorMessages() {
        return errorMessages;
    }

    public void setFilePath(List<String> filePath) {
        this.filePath = filePath;
    }
}
